package com.dlu.safe_construction.service.impl;

import com.auth0.jwt.interfaces.Claim;
import com.dlu.safe_construction.common.ApiResult;
import com.dlu.safe_construction.common.LoginContext;
import com.dlu.safe_construction.common.utils.JWTUtils;
import com.dlu.safe_construction.common.utils.StringUtils;
import com.dlu.safe_construction.common.utils.Utils;
import com.dlu.safe_construction.dto.ManagerEditDTO;
import com.dlu.safe_construction.dto.ManagerInfoDTO;
import com.dlu.safe_construction.mapper.ManagerMapper;
import com.dlu.safe_construction.model.Manager;
import com.dlu.safe_construction.service.ManagerService;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.User;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * Created by  lijiaxing on 2022/3/30 20:14
 *
 * @author lijiaxing
 */
@Service
@Slf4j
public class ManagerServiceImpl implements ManagerService {

    private static Integer phoneLength = 11;

    @Resource
    private ManagerMapper managerMapper;

    private Map<String, Claim> verifyToken(String token) {
        try {
            return JWTUtils.verifyToken(token);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public ApiResult<Void> auth(String token) {
        Map<String, Claim> map = verifyToken(token);
        if (Utils.isNotEmpty(map)) {
            return ApiResult.success();
        } else {
            log.error("check token failed please check token.token={}", token);
            return ApiResult.fail(500);
        }
    }

    @Override
    public ApiResult<String> login(String accountId, String password) {
        Manager manager = null;
        if (accountId.length() == phoneLength) {
            manager = managerMapper.selectByPhone(accountId);
        } else {
            manager = managerMapper.selectByPrimaryKey(accountId);
        }
        if (Utils.isNotEmpty(manager)) {
            try {
                return ApiResult.success(JWTUtils.createToken(manager));
            } catch (Exception e) {
                e.printStackTrace();
            }
            log.error("JWTUtils::createToken failed please check params. manager={}", manager);
            return ApiResult.fail(5000);
        } else {
            log.error("Check user failed , please check your param. accountId={},password={}", accountId, password);
            return ApiResult.fail(5001, "用户名或密码错误，请重试。");
        }
    }

    @Override
    public ApiResult<ManagerInfoDTO> info(String token) {
        Map<String, Claim> map = verifyToken(token);
        String userId = map.get("userId").asString();
        String userPhone = map.get("userPhone").asString();
        String userName = map.get("userName").asString();

        return ApiResult.success(ManagerInfoDTO.fromInfoCreate(userId, userPhone, userName));
    }

    @Override
    public ApiResult<Void> edit(ManagerEditDTO editDTO) {

        if (!LoginContext.getManager().getUserPasswd().equals(editDTO.getPasswordOld())) {
            log.error("passwordOld is failed, please checked.params={}", editDTO);
            return ApiResult.fail(6001,"旧密码错误");
        } else if (Utils.isEmpty(editDTO.getPasswordNew())) {
            log.error("new password can not be empty,please checked. params={}", editDTO);
            return ApiResult.fail(6002,"新密码不能为空");
        } else if (editDTO.getPasswordNew().equals(editDTO.getPasswordOld())) {
            log.error("new password is the same with old password, please checked. params={}", editDTO);
            return ApiResult.fail(6003,"新旧密码不能相同");
        } else {
            String userId = LoginContext.getManager().getUserId();
            if(StringUtils.isEmpty(userId)){
                log.error("can not find userId from LoginContext,please check.");
                return ApiResult.fail(6004,"网络错误，请联系管理员。");
            }
            Manager manager = managerMapper.selectByPrimaryKey(userId);
            if(Utils.isNotEmpty(manager)){
                manager.setUserPasswd(editDTO.getPasswordNew());
                manager.setUserPhone(editDTO.getPhone());
                int ret = managerMapper.updateByPrimaryKey(manager);
                if(ret>0){
                    return ApiResult.success();
                }
                log.error("can not update database,please check.param={}",manager);
            }
            log.error("can not find manager by userId,please check.userId={}",userId);
        }
        return ApiResult.fail(6004,"错误！请联系管理员！！");
    }
}
